package xyz.ranyh.jobclient.http;

import android.os.AsyncTask;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import xyz.ranyh.jobclient.util.JobBean;
import xyz.ranyh.jobclient.util.JobsListAdapter;

/**
 * Created by zhaoshengping on 2016/12/28.
 */

public class GetJobsListTask extends AsyncTask {

    private ArrayList<JobBean> jobs;
    private String url;
    private String responseData;
    private JobsListAdapter jobsListAdapter;
    private GetJoblistener listener;

    public GetJoblistener getGetJoblistener() {
        return listener;
    }

    public void setGetJoblistener(GetJoblistener listener) {
        this.listener = listener;
    }

    public interface GetJoblistener {
        void onSuccess(JSONObject res);
    }

    public ArrayList<JobBean> getJobs() {
        return jobs;
    }

    public void setJobs(ArrayList<JobBean> jobs) {
        this.jobs = jobs;
    }

    public GetJobsListTask(String url,ArrayList<JobBean> jobs,JobsListAdapter jobsListAdapter) {
        setJobs(jobs);
        this.jobsListAdapter = jobsListAdapter;
        this.url = url;
    }
    public GetJobsListTask(String url,ArrayList<JobBean> jobs) {
        setJobs(jobs);
        this.url = url;
    }

    private void sendHttp(String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        String credential = Credentials.basic(Resource.getInstance().token, "");
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", credential)
                .addHeader("accept", "application/json")
                .build();
        try {
            this.responseData = "";
            Response response = okHttpClient.newCall(request).execute();
            this.responseData = response.body().string();
//            Log.i("response data", this.responseData);
        } catch (IOException e) {
            e.printStackTrace();
            this.cancel(true);
        }
    }

    @Override
    protected Object doInBackground(Object[] objects) {
        sendHttp(this.url);
        return null;
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        if (this.responseData == null) return;
        try {
            JSONObject res = new JSONObject(this.responseData);
            listener.onSuccess(res);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
